package com.github.zyt.webuploader.contorller;

import ch.qos.logback.classic.Logger;
import com.github.zyt.webuploader.util.FileUtil;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;

/**
 * 分片上传Controller
 */
@Controller
@RequestMapping("upload")
public class UploadController {

    private static Logger logger = (Logger) LoggerFactory.getLogger(UploadController.class);

    /**
     * 上传路径
     */
    private static String uploadPath = "D:/upload";
    private static String uploadFile="D:\\upload\\";

    /**
     * 跳转到首页
     *
     * @return
     */
    @GetMapping("index")
    public String index() {
        return "index";
    }
    @GetMapping("uploadFile")
    public String uploadFile(String  id, ModelMap modelMapt)
    {
        logger.info("该id是多少"+id);
        modelMapt.addAttribute("id",id);
        return "uploadFile";
    }



    @PostMapping("/searchfor")
    @ResponseBody
    public boolean   searchfor(String id) {
        boolean isFalse=false;
        File file = new File(uploadPath);
        List<File> files = FileUtil.getFiles(file);
        if(CollectionUtils.isEmpty(files)){// 判断数组是否为空
            return isFalse;
        }
        for (int i = 0; i < files.size(); i++) {
            String name = files.get(i).getName();
            String nameDoc = name.substring(0, name.indexOf("."));;
            logger.info("===="+name+"---"+nameDoc);
            if(nameDoc.equals(id)){//如果有这个文件的话，就true;
                isFalse=true;
            }
        }
       return isFalse;
    }



    @RequestMapping(value="/download",method = RequestMethod.GET)
    public void download( HttpServletResponse response,HttpServletRequest request){
        //要上传的文件名字
        String fileName = request.getParameter("id")+".docx";
        //通过文件的保存文件夹路径加上文件的名字来获得文件
        File file=new File(uploadFile,fileName);
        //当文件存在
        if(file.exists()){
            //首先设置响应的内容格式是force-download，那么你一旦点击下载按钮就会自动下载文件了
            response.setContentType("application/force-download");
            //通过设置头信息给文件命名，也即是，在前端，文件流被接受完还原成原文件的时候会以你传递的文件名来命名
            response.addHeader("Content-Disposition",String.format("attachment; filename=\"%s\"", file.getName()));
            //进行读写操作
            byte[]buffer=new byte[1024];
            FileInputStream fis=null;
            BufferedInputStream bis=null;
            try{
                fis=new FileInputStream(file);
                bis=new BufferedInputStream(fis);
                OutputStream os=response.getOutputStream();
                //从源文件中读
                int i=bis.read(buffer);
                while(i!=-1){
                    //写到response的输出流中
                    os.write(buffer,0,i);
                    i=bis.read(buffer);
                }
            }catch (IOException e){
                e.printStackTrace();
            }finally {
                //善后工作，关闭各种流
                try {
                    if(bis!=null){
                        bis.close();
                    }
                    if(fis!=null){
                        fis.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
    }

}
